import tkinter as tk
from tkinter import ttk

class AutoScrollFrame(tk.Frame):
    def __init__(self, master, **kwargs):
        super().__init__(master, **kwargs)
        
        # 创建画布和滚动条
        self.canvas = tk.Canvas(self, highlightthickness=0)
        self.v_scroll = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
        
        # 配置画布滚动
        self.canvas.configure(yscrollcommand=self.v_scroll.set, background=kwargs.get('background', None))
        self.inner_frame = tk.Frame(self.canvas)
        
        # 打包组件
        self.canvas.pack(side="left", fill="both", expand=True)
        self.v_scroll.pack(side="right", fill="y")
        
        # 创建窗口并绑定事件
        self.canvas.create_window((0,0), window=self.inner_frame, anchor="nw")
        self.inner_frame.bind("<Configure>", self._check_scroll)
        self.canvas.bind("<Configure>", self._update_scrollregion)
        self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)

    def _check_scroll(self, event=None):
        """检测是否需要显示滚动条"""
        # 计算内容高度与可视高度
        content_height = self.inner_frame.winfo_height()
        canvas_height = self.canvas.winfo_height()
        
        # 动态显示/隐藏滚动条
        if content_height > canvas_height:
            self.v_scroll.pack(side="right", fill="y")
        else:
            self.v_scroll.pack_forget()
        
        # 更新滚动范围
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

    def _update_scrollregion(self, event=None):
        """更新画布滚动区域"""
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))
        self._check_scroll()

    def _on_mousewheel(self, event):
        """鼠标滚轮滚动支持"""
        if self.v_scroll.winfo_ismapped():
            self.canvas.yview_scroll(int(-1*(event.delta/120)), "units")

    @property
    def content_frame(self):
        """获取内容区域的frame"""
        return self.inner_frame
